﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace ColorGrabber
{
    /// <summary>
    /// Thanks to CLaRGe @ http://stackoverflow.com/questions/753132/how-do-i-get-the-colour-of-a-pixel-at-x-y-using-c
    /// Users Pinvoke to get the pixel color as specified coordinates
    /// </summary>
    internal static class ColorGetter
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hwnd);

        [DllImport("user32.dll")]
        static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

        [DllImport("gdi32.dll")]
        static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

        /// <summary>
        /// Gets the Color of specified pixel at point with coordinates x and y
        /// </summary>
        /// <param name="x">X axes int value for the point to check</param>
        /// <param name="y">Y axes int value for the point to check<</param>
        /// <returns></returns>
        internal static System.Drawing.Color GetPixelColor(int x, int y)
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            uint pixel = GetPixel(hdc, x, y);
            ReleaseDC(IntPtr.Zero, hdc);
            Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                         (int)(pixel & 0x0000FF00) >> 8,
                         (int)(pixel & 0x00FF0000) >> 16);
            return color;
        }
    }
}
